﻿using System;
using System.Web.Caching;
using System.Reflection;

namespace MVCFoto.DALFactory
{
    public class Factory
    {
        private static object syncLock = new object();
        public static T Create<T> (string className)
        {
            string cacheKey = String.Format("MF_Cache_DALFactory_{0}_{1}", typeof(T), className);
            object result = System.Web.HttpRuntime.Cache.Get(cacheKey);
            if (result == null)
            {
                lock (syncLock)
                {
                    result = System.Web.HttpRuntime.Cache.Get(cacheKey);
                    if (result == null)
                    {
                        /// Look up the DAL implementation we should be using
                        string path = System.Configuration.ConfigurationManager.AppSettings["WebDAL"];
                        className = String.Format("{0}.{1}", path, className);
                        // Using the evidence given in the config file load the appropriate assembly and class
                        result = (T)Assembly.Load(path).CreateInstance(className);                        
                        if (result != null)
                            System.Web.HttpRuntime.Cache.Add(cacheKey, result,new CacheDependency(System.Web.HttpContext.Current.Server.MapPath("~/")),
                                DateTime.Now.Add(TimeSpan.FromDays(365)), TimeSpan.Zero, CacheItemPriority.Normal, null);
                    }

                }
            }
            return (T)result;
        }
    }
}